package com.bookstore;

import com.bookstore.db.BookStoreDB;
import com.bookstore.db.BookStoreDao;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class ListBookActivity extends MenuListActivity {

	private static final int ACTIVITY_BOOK_DETAIL = 3;
	
	private Long mRowId;
	private BookStoreDao dao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (dao==null){
        	dao = new BookStoreDao(this);
            dao.open();
        }
		setContentView(R.layout.book_list);
		Bundle extras = getIntent().getExtras();
		mRowId = extras != null ? extras.getLong(BookStoreDB.KEY_ROWID) : null;
		if (mRowId!=null && mRowId>0){
			this.loadBooks();
			registerForContextMenu(getListView());
		}			
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
	    super.onListItemClick(l, v, position, id);
	    Intent i = new Intent(this, BookDetailActivity.class);
	    i.putExtra(BookStoreDB.KEY_ROWID, id);
	    startActivityForResult(i, ACTIVITY_BOOK_DETAIL);
	}
	
	
	private void loadBooks() {
		Cursor c = dao.fetchAllLibrosByCategoria(this.mRowId);
		startManagingCursor(c);
		String[] from = new String[] { "title", "autor" };
		int[] to = new int[] { R.id.labelBook, R.id.autorBook };
		SimpleCursorAdapter books = new SimpleCursorAdapter(this,
				R.layout.books_row, c, from, to);
		setListAdapter(books);
	}
}
